package com.liang.maogouyuyin.widget.popup

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import com.liang.maogouyuyin.R
import com.liang.publics.ad.ads.AsService
import com.liang.publics.util.SharedPreferencesUtil
import com.lxj.xpopup.core.CenterPopupView

class MainPopup(context: Context): CenterPopupView(context) {

    private var adService: AsService? = null

    override fun getImplLayoutId(): Int {
        return R.layout.popup_main
    }

    override fun onCreate() {
        super.onCreate()

        val feedContainerExitDialog = findViewById<FrameLayout>(R.id.feed_container_exit_dialog)

        if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD)) {
            adService = AsService()
            adService?.apply {
                initAd("feed", context, context.getString(R.string.feed_native_media_id), feedContainerExitDialog)
                showAd("feed", activity)
                initAd("reward", context, context.getString(R.string.reward_media_id), null)
            }
        }

        val popupDelete = findViewById<ImageView>(R.id.popup_main_delete)
        popupDelete.setOnClickListener {
            if (SharedPreferencesUtil.getStatus(SharedPreferencesUtil.IF_AD))
                adService?.showAd("reward", activity)
            dismiss()
        }

        val popupButton = findViewById<TextView>(R.id.popup_main_button)
        popupButton.setOnClickListener {
            SharedPreferencesUtil.saveStatus("MainPopup", true)
            dismiss()
        }

        val popupText = findViewById<TextView>(R.id.popup_main_text)
        val text = "您可免费解锁\n互动/记录等高级功能"

        val spannableStringBuilder = SpannableStringBuilder(text)
        spannableStringBuilder.apply {
            setSpan(StyleSpan(Typeface.BOLD), 0, text.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val redStart = text.indexOf("免费")
            setSpan(ForegroundColorSpan(Color.parseColor("#ff540b")), redStart, redStart + "免费".length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

            val blueStart = text.indexOf("互动/记录")
            setSpan(ForegroundColorSpan(Color.parseColor("#0f3bdf")), blueStart, blueStart + "互动/记录".length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        }

        popupText.typeface = Typeface.DEFAULT
        popupText.text = spannableStringBuilder
    }
}